#pragma once

#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <string.h>
#include <strings.h>
#include <functional>
#include <unordered_map>
#include "log.hpp"

Log udplog;
using func_t = std::function<std::string(const std::string&)>;

enum{
    SOCKET_ERR = 1,
    BIND_ERR
};

uint16_t defaultport = 8080;
std::string defaultip = "0.0.0.0";
const int UDPSIZE = 1024;

class UdpServer
{
public:
    UdpServer(const uint16_t &port = defaultport,const std::string &ip = defaultip)
        :_port(port)
        ,_ip(ip)
        ,_sockfd(0)
    {}

    void Init()
    {
        // 1. 创建udp socket(套接字)
        _sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd < 0)
        {
            udplog(Fatal,"socket create error, _sockfd: %d", _sockfd);
            exit(SOCKET_ERR);
        }
        udplog(Info,"socket create success, socket: %d",_sockfd);

        // 2. bind socket(绑定套接字)
        // struct sockaddr_in: 网络通信所用结构体
        struct sockaddr_in local;
        // 主要用于将一段内存区域的内容清零
        bzero(&local,sizeof(local));
        local.sin_family = AF_INET;
        // htons():主机序列转化为网络序列
        local.sin_port = htons(_port);         // 需要保证我的端口号是网络字节序列的，因为该端口号是要给对方发送的
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_addr.s_addr = htons(INADDR_ANY);     // INADDR_ANY: 0.0.0.0表示任意地址

        if(bind(_sockfd,(const struct sockaddr*)&local,sizeof(local)) < 0)
        {
            udplog(Fatal,"bind error, errno: %d, err string: %s",errno,strerror(errno));
            exit(BIND_ERR);
        }
        udplog(Info, "bind success, errno: %d, err string: %s", errno,strerror(errno));
    }
    // 检查是否新用户
    void CheckUser(const struct sockaddr_in &client,const std::string clientip,uint16_t clientport)
    {
        auto iter = _user_online.find(clientip);
        // 新用户则插入
        if(iter == _user_online.end())
        {
            _user_online.insert({clientip,client});
            std::cout << "[" << clientip << ":" << clientport << "] add to online user." << std::endl;
        }
    }
    // 返回服务器响应的数据
    void Broadcast(const std::string &info,const std::string clientip,uint16_t clientport)
    {
        for(const auto &user:_user_online)
        {
            std::string message = "[";
            message += clientip;
            message += ":";
            message += std::to_string(clientport);
            message += "]# ";
            message += info;
            socklen_t len = sizeof(user.second);

            sendto(_sockfd,message.c_str(),message.size(),0,(const sockaddr*)&user.second,sizeof(user.second));
        }
    }
    void Run()
    {
        char inbuffer[UDPSIZE];
        while(true)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            
            memset(inbuffer,0,sizeof(inbuffer));
            // recvfrom：从套接字接收一个消息
            ssize_t n = recvfrom(_sockfd,inbuffer,sizeof(inbuffer)-1,0,(struct sockaddr*)&client,&len);
            if(n < 0)
            {
                udplog(Warning, "recvfrom error, errno: %d, err string: %s",errno, strerror(errno));
                continue;
            }            

            // 检查是否新用户
            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);
            CheckUser(client,clientip,clientport);
            
            // 向客户端发送服务器响应的数据
            std::string info = inbuffer;
            Broadcast(info,clientip,clientport);
        }
    }

    ~UdpServer()
    {
        if(_sockfd > 0)
            close(_sockfd);
    }
private:
    int _sockfd;            // 网络文件描述符
    std::string _ip;        // 地址
    uint16_t _port;         // 表明服务器进程的端口号
    std::unordered_map<std::string,struct sockaddr_in> _user_online;
};